<?php


namespace App\Http\service;
use App\Engine\TokenService;
use App\Exceptions\ApiException;
use App\Models\TurntableActive as ActiveModel;
use Illuminate\Support\Facades\Cache;
use App\Models\User as UserModel;
use Illuminate\Support\Facades\DB;
use Exception;
use function app\Utils\go;
use App\Models\TurntableLog as LogModel;


class ActiveService
{
    private $activeModel;
    private $uid;
    private $userModel;
    private $logModel;

    public function __construct()
    {
        $this->activeModel=new ActiveModel();
        $this->uid=TokenService::getCurrentUid();
        $this->userModel=new UserModel();
        $this->logModel=new LogModel();
    }

    /**
     * 开启抽奖
     */
    public function start_draw()
    {
        $res=Cache::lock("active_{$this->uid}")->get(function (){
            DB::beginTransaction();
            try {
                $data=$this->activeModel->get();
                $user=$this->userModel->where("id",$this->uid)->first();
                if ($user["draw_times"]==0)
                    throw new ApiException("抽奖次数不足,可观看项目或者分享获取抽奖次数");
                $probability=array();
                foreach ($data as $k=>$v){
                    $probability[]=$v["weight"];
                }
                $index=$this->get_prize($probability);
                $res=$data[$index];

                $count=$this->activeModel->count();
                $wight=$this->activeModel->sum("weight");
                $index_wight=$this->activeModel->where("id","<=",$res["id"])->sum("weight");
                $rand=rand(3,10);
                $res["power"]=3.6*$rand-($index_wight/$wight*360)/100+0.1;
                $user->decrement("draw_times",1);
                if($res["type"]==1){
                    $create=[
                        "uid"=>$this->uid,
                        "content"=>$res["reward"],
                        "image"=>$res["icon"],
                        "state"=>0
                    ];
                    $this->logModel->create($create);
                }
                DB::commit();
                return  $res;
            }catch (Exception $exception){
                DB::rollBack();
                throw new ApiException($exception->getMessage());
            }
        });
        return $res;
    }

    private function get_prize($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }
}
